package com.demo.practiceui.views.interactive;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

/**
 * 自定义进度条（线性 + 圆形）
 * 核心知识点：
 * 1. 线性进度条：drawRect + 宽度控制
 * 2. 圆形进度条：drawArc + 角度控制
 * 3. 进度值映射
 */
public class CustomProgressView extends View {

    // 进度数据
    private float progress = 0;     // 0-100
    private float maxProgress = 100;

    // 类型
    private boolean isCircular = false;  // false=线性, true=圆形

    // 画笔
    private Paint bgPaint;          // 背景画笔
    private Paint progressPaint;    // 进度画笔
    private Paint textPaint;        // 文字画笔

    // 尺寸
    private int width;
    private int height;
    private float centerX;
    private float centerY;

    // 线性进度条参数
    private float barHeight = 40f;
    private float cornerRadius = 20f;
    // ========== 修改开始：添加线性进度条复用对象 ==========
    private RectF linearBgRect = new RectF();
    private RectF linearProgressRect = new RectF();
    private float linearPaddingHorizontal = 50f;
    private float linearTop;
    private float linearBottom;
    private float linearMaxWidth;
    // ========== 修改结束 ==========

    // 圆形进度条参数
    private float radius;
    private float strokeWidth = 30f;
    private RectF rectF;

    public CustomProgressView(Context context) {
        this(context, null);
    }

    public CustomProgressView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomProgressView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        // 背景画笔
        bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        bgPaint.setColor(Color.parseColor("#E0E0E0"));
        bgPaint.setStyle(Paint.Style.FILL);

        // 进度画笔
        progressPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        progressPaint.setColor(Color.parseColor("#4CAF50"));
        progressPaint.setStyle(Paint.Style.FILL);
        progressPaint.setStrokeCap(Paint.Cap.ROUND);

        // 文字画笔
        textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        textPaint.setColor(Color.parseColor("#333333"));
        textPaint.setTextSize(36f);
        textPaint.setTextAlign(Paint.Align.CENTER);

        rectF = new RectF();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        if (widthMode == MeasureSpec.AT_MOST) {
            width = 600;
        }
        if (heightMode == MeasureSpec.AT_MOST) {
            height = isCircular ? 400 : 150;
        }
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;
        centerX = width / 2f;
        centerY = height / 2f;

        if (isCircular) {
            radius = Math.min(width, height) / 2f - strokeWidth - 50;
            rectF.set(centerX - radius, centerY - radius,
                    centerX + radius, centerY + radius);
        } else {
            // ========== 修改开始：在线性模式下预先计算固定值 ==========
            linearTop = centerY - barHeight / 2;
            linearBottom = centerY + barHeight / 2;
            linearMaxWidth = width - 2 * linearPaddingHorizontal;

            // 预先设置背景矩形（固定部分）
            linearBgRect.set(linearPaddingHorizontal, linearTop,
                    width - linearPaddingHorizontal, linearBottom);
            // ========== 修改结束 ==========
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (isCircular) {
            drawCircularProgress(canvas);
        } else {
            drawLinearProgress(canvas);
        }
    }

    /**
     * 绘制线性进度条
     */
    private void drawLinearProgress(Canvas canvas) {
        // ========== 修改开始：使用预先计算好的值，不再创建新RectF ==========
        // 1. 绘制背景 - 使用复用对象
        canvas.drawRoundRect(linearBgRect, cornerRadius, cornerRadius, bgPaint);

        // 2. 绘制进度
        if (progress > 0) {
            float progressWidth = linearMaxWidth * (progress / maxProgress);
            linearProgressRect.set(linearPaddingHorizontal, linearTop,
                    linearPaddingHorizontal + progressWidth, linearBottom);

            // 根据进度改变颜色
            if (progress < 30) {
                progressPaint.setColor(Color.parseColor("#FF5722"));  // 红色
            } else if (progress < 70) {
                progressPaint.setColor(Color.parseColor("#FFC107"));  // 黄色
            } else {
                progressPaint.setColor(Color.parseColor("#4CAF50"));  // 绿色
            }

            canvas.drawRoundRect(linearProgressRect, cornerRadius, cornerRadius, progressPaint);
        }

        // 3. 绘制进度文字
        String text = String.format("%.0f%%", progress);
        canvas.drawText(text, centerX, linearTop - 30, textPaint);
        // ========== 修改结束 ==========
    }

    /**
     * 绘制圆形进度条
     */
    private void drawCircularProgress(Canvas canvas) {
        // 1. 绘制背景圆环
        bgPaint.setStyle(Paint.Style.STROKE);
        bgPaint.setStrokeWidth(strokeWidth);
        canvas.drawCircle(centerX, centerY, radius, bgPaint);

        // 2. 绘制进度圆弧
        if (progress > 0) {
            progressPaint.setStyle(Paint.Style.STROKE);
            progressPaint.setStrokeWidth(strokeWidth);
            progressPaint.setStrokeCap(Paint.Cap.ROUND);

            // 计算进度角度（从顶部-90度开始，顺时针）
            float sweepAngle = 360f * (progress / maxProgress);

            // 根据进度改变颜色
            if (progress < 30) {
                progressPaint.setColor(Color.parseColor("#FF5722"));
            } else if (progress < 70) {
                progressPaint.setColor(Color.parseColor("#FFC107"));
            } else {
                progressPaint.setColor(Color.parseColor("#4CAF50"));
            }

            canvas.drawArc(rectF, -90, sweepAngle, false, progressPaint);
        }

        // 3. 绘制中心文字
        textPaint.setTextSize(56f);
        textPaint.setColor(Color.parseColor("#333333"));
        canvas.drawText(String.format("%.0f%%", progress), centerX, centerY + 20, textPaint);

        // 绘制提示文字
        textPaint.setTextSize(28f);
        textPaint.setColor(Color.parseColor("#999999"));
        canvas.drawText("完成度", centerX, centerY + 60, textPaint);
    }

    /**
     * 设置进度（带动画效果）
     */
    public void setProgress(float progress) {
        this.progress = Math.max(0, Math.min(maxProgress, progress));
        invalidate();
    }

    /**
     * 设置进度类型
     */
    public void setCircular(boolean circular) {
        this.isCircular = circular;
        requestLayout();  // 重新测量和布局
        invalidate();
    }

    /**
     * 获取当前进度
     */
    public float getProgress() {
        return progress;
    }
}